package com.wh1200.mybatis.xmlless.model.component

import com.wh1200.mybatis.xmlless.dialect.DialectFactory
import com.wh1200.mybatis.xmlless.enums.XmllessDbType
import com.wh1200.mybatis.xmlless.model.TableName
import com.wh1200.mybatis.xmlless.model.XmllessTableInfo
import com.wh1200.mybatis.xmlless.resolver.ColumnsResolver
import net.sf.jsqlparser.expression.ExpressionVisitorAdapter
import net.sf.jsqlparser.expression.Function
import net.sf.jsqlparser.schema.Column
import net.sf.jsqlparser.schema.Table

/**
 * @author 吴昊
 * @date 2024/01/18
 * @version 1.0
 * @since v4.0.0
 */
class ReplacePropertyToJoinColumnVisitor(
    private val tableInfo: XmllessTableInfo,
    private val targetTable: TableName,
    private val dbType: XmllessDbType
) : ExpressionVisitorAdapter() {

  override fun visit(column: Column) {
    if (column.table != null) {
      return
    }
    val col = ColumnsResolver.resolveJoinOnColumn(
        "", column.toString(), tableInfo
    )
    column.table = Table(targetTable.getAliasOrName())
    column.columnName = col
  }

  override fun visit(function: Function) {
    if (function.name.lowercase() in listOf("date", "month", "year")) {
      val dialect = DialectFactory.getDialect(dbType)
      dialect.replaceDateFunction(function)
    }
    super.visit(function)
  }

}
